const incID = require("../functions/incID");
const Reserves = require("../models/Reserves")
const Users = require("../models/Users")
const Plays = require("../models/Plays")

const createReserve = async (req, res) => {
    try {
        console.log(req.body)
        const ReservesArray = await Reserves.find({ id_play: req.body.id_play });
        for (item in ReservesArray) {
            if (req.user._id == ReservesArray[item]["initiator"]) {
                return res.status(400).json({ error_msg: '您为车队发起人，请先取消组局' });
            }
            for (i in ReservesArray[item]["member"]) {
                if (req.user._id == ReservesArray[item]["member"][i]) {
                    return res.status(400).json({ error_msg: '您已加入某车队' });
                }
            }
        }

        const savequery = {
            id_reserve: await incID("reserve"),
            id_play: req.body.id_play,
            initiator: req.user._id,
            starttime: req.body.starttime,
            num_limit: req.body.num_limit
        }
        const reservescreate = await Reserves(savequery).save()

        const finduser = await Users.findById(req.user._id)
        finduser.reserves_played.push(reservescreate._id)
        finduser.save()

        const findplay = await Plays.findById(req.body.id_play)
        findplay.reserves.push(reservescreate._id)
        findplay.save()

        return res.status(200).json({ success: reservescreate });
    } catch (err) {
        return res.status(400).json({ error_msg: err.message });
    }
}


const joinReserve = async (req, res) => {
    try {
        const ReservesArray = await Reserves.find({ id_play: req.body.id_play });
        for (item in ReservesArray) {
            if (req.user._id == ReservesArray[item]["initiator"]) {
                return res.status(400).json({ error_msg: '您为车队发起人，请先取消组局' });
            }
            for (i in ReservesArray[item]["member"]) {
                if (req.user._id == ReservesArray[item]["member"][i]) {
                    return res.status(400).json({ error_msg: '您已加入某车队' });
                }
            }
        }
        const ReserveExist = await Reserves.findById(req.body.id_reserve);
        if (!ReserveExist) {
            return res.status(400).json({ error_msg: '无该车队' });
        }
        ReserveExist["member"].push(req.user._id)
        const reservesjoin = await ReserveExist.save()

        const finduser = await Users.findById(req.user._id)
        finduser.reserves_played.push(req.body.id_reserve)
        finduser.save()


        return res.status(200).json({ success: reservesjoin });

    } catch (err) {
        return res.status(400).json({ error_msg: err.message });
    }
}

const removeReserve = async (req, res) => {
    try {
        const reserveExist = await Reserves.findById(req.body._id);
        if (reserveExist) {
            const reserveremoved = await reserveExist.remove()
            return res.status(200).json({ success: reserveremoved });
        }
        else {
            return res.status(400).json({ error_msg: "未找到该车" });
        }

    } catch (err) {
        return res.status(400).json({ error_msg: err.message });
    }
}

const quitReserve = async (req, res) => {
    try {
        const reserveExist = await Reserves.findById(req.body._id);

        if (reserveExist) {
            if (req.body.id_user == reserveExist["initiator"]) {
                return res.status(400).json({ error_msg: '您为车队发起人，请直接取消组局' });
            }
            for (item in reserveExist["member"]) {
                if (req.body.id_user == reserveExist["member"][item]) {
                    reserveExist["member"].splice(item, 1)
                    console.log(reserveExist)
                    const reservequit = await reserveExist.save()
                    return res.status(200).json({ success: reservequit });
                } else {
                    return res.status(400).json({ error_msg: "您未加入该车队" });
                }
            }
        }

        else {
            return res.status(400).json({ error_msg: "未找到该车" });
        }

    } catch (err) {
        return res.status(400).json({ error_msg: err.message });
    }
}


const updateReserve = async (req, res) => {
    try {
        const playExist = await Reserves.findById(req.body._id);
        if (playExist) {
            const savequery = req.body
            delete savequery._id
            for (item in savequery) {
                if (typeof (savequery[item]) == "object") {
                    playExist[item] = { ...playExist[item], ...savequery[item] }
                } else {
                    playExist[item] = savequery[item]
                }
            }
            const playupdated = await playExist.save()
            return res.status(200).json({ success: playupdated });
        }
        else {
            return res.status(400).json({ error_msg: "未找到车队" });
        }
    } catch (err) {
        return res.status(400).json({ error_msg: err.message });
    }
}

const getReserve = async (req, res) => {
    try {
        const foundquery = req.query
        // for (item in foundquery) {
        //     console.log(typefoundquery[item])

        //     foundquery[item] = eval("/" + foundquery[item] + "/")
        // }
        const playfound = await Reserves.find(foundquery).populate("id_play initiator member")
        if (!playfound) {
            return res.status(200).json({ error_msg: "未找到车队" });
        }
        return res.status(200).json({ success: playfound });
    }
    catch (err) {
        return res.status(400).json({ error_msg: err.message });
    }
}



module.exports = { createReserve, joinReserve, removeReserve, quitReserve, getReserve, updateReserve }